import React, { Component } from 'react';
import { connect } from 'dva';
import styles from '../index.css';
// import { Dispatch, AnyAction } from 'redux';
import { Button, Table, Select, Input, Pagination, Modal, Tree, message, Spin, Icon } from 'antd';
import { DeviceListsItem } from '@/models/connect';

const { TreeNode } = Tree;
const { Option } = Select;
const { Column } = Table;

interface DeviceListsProps {
  deviceList?: DeviceListsItem[];
  loading: boolean;
}
// @connect()

class DevicePermissionManage extends Component<DeviceListsProps> {
  constructor(props: DeviceListsProps) {
    super(props);
    this.state = {
      isShowModel: false, // 打开弹窗
      expandedKeys: [], //树形展开的节点key
      autoExpandParent: true, //自动展开父级
      checkedKeys: [], // 选中的节点id
      selectedKeys: [], // 点击的节点id
      curRoleId: undefined, // 点击表格某一行的角色Id
      curRoleName: '', // 点击表格某一行的角色名称
      selcTree: [], // 树形数据
      pageTotal: 0, // 列表总数
      tableData: [], // 表格数据
      roleId: '', // 搜索框的角色id
      roleName: '', // 搜索框的角色名称
      pageNum: 1, // 当前页
      pageSize: 10, // 每页展示数据的条数
      roleDevicePowerList: [], // 选中节点的数据
      isPatching: false, // 是否正在加载中
    };
  }
  componentWillMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'systemDevice/applyDeviceLists',
      payload: {
        roleId: this.state.roleId,
        roleName: this.state.roleName,
        pageNum: 1,
        pageSize: 10,
      },
    }).then(() => {
      const { systemDevice } = this.props;
      this.setState({ tableData: systemDevice.rows, pageTotal: systemDevice.total });
    });
  }
  // 角色状态筛选
  handleChange(val: any) {
    console.log(val);
  }
  //改变页码数
  onPageChange = (pageNo: Number) => {
    console.log('doSomething' + pageNo);
    const { dispatch } = this.props;
    dispatch({
      type: 'systemDevice/applyDeviceLists',
      payload: {
        roleId: this.state.roleId,
        roleName: this.state.roleName,
        pageNum: pageNo,
        pageSize: 10,
      },
    }).then(() => {
      const { systemDevice } = this.props;
      this.setState({ tableData: systemDevice.rows, pageTotal: systemDevice.total });
    });
  };
  // 点击搜索按钮 查询数据
  searchHandle() {
    const { dispatch } = this.props;
    dispatch({
      type: 'systemDevice/applyDeviceLists',
      payload: {
        roleId: this.state.roleId,
        roleName: this.state.roleName,
        pageNum: 1,
        pageSize: 10,
      },
    }).then(() => {
      const { systemDevice } = this.props;
      this.setState({ tableData: systemDevice.rows, pageTotal: systemDevice.total });
    });
  }
  // 监听展开
  onExpand = (expandedKeys: Array<string>) => {
    console.log('onExpand', expandedKeys);
    // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.
    this.setState({
      expandedKeys,
      autoExpandParent: false,
    });
  };
  // 监听选中
  onCheck = (checkedKeys: Array<string>, e: any) => {
    let roleDevicePowerList = [];
    e.checkedNodes.forEach((item: any, idx: number) => {
      if (!!item.props.dataRef.deviceId) {
        roleDevicePowerList.push({
          deviceId: item.props.dataRef.deviceId,
          roleDevicePowerId: item.props.dataRef.roleDevicePowerId,
        });
      }
    });
    this.setState({ checkedKeys, roleDevicePowerList });
  };

  // onSelect = (selectedKeys: Array<string>, info: any) => {
  //   console.log('onSelect', selectedKeys);
  //   this.setState({ selectedKeys });
  // };
  // 渲染树形数据
  renderTreeNodes = (data: Array<any>) =>
    data.map(item => {
      if (item.list) {
        return (
          <TreeNode
            title={item.stuts ? item.deviceName : item.typeName}
            key={item.stuts ? item.deviceId : item.deviceTypeNo}
            dataRef={item}
          >
            {this.renderTreeNodes(item.list)}
          </TreeNode>
        );
      }
      return (
        <TreeNode
          key={item.stuts ? item.deviceId : item.deviceTypeNo}
          title={item.stuts ? item.deviceName : item.typeName}
          dataRef={item}
          {...item}
        />
      );
    });
  //获取选中的节点
  getCheckedKeys(tree: Array<any>, check_keys: Array<any>) {
    tree.forEach((e: any) => {
      if (e.stuts && e.stuts === '1') {
        check_keys.push(e.deviceId);
      } else {
        if (e.list && e.list.length) {
          this.getCheckedKeys(e.list, check_keys);
        }
      }
    });
  }
  // 请求后台树形数据
  getTreeData(_record: any) {
    console.log(_record);
    const { dispatch } = this.props;
    this.setState({ isPatching: true });
    dispatch({
      type: 'systemDevice/applyDeviceTreeData',
      payload: { roleId: _record.roleId },
    }).then(() => {
      const treeData = JSON.parse(JSON.stringify(this.props.treeData));
      let check_keys:any = [];
      this.getCheckedKeys(treeData, check_keys);
      this.setState({
        checkedKeys:check_keys,
        selcTree: treeData,
        isShowModel: true,
        curRoleId: _record.roleId,
        curRoleName: _record.roleName,
        isPatching: false,
      });
    });
  }
  addDevicePower() {
    if (this.state.roleDevicePowerList.length) {
      const { dispatch } = this.props;
      dispatch({
        type: 'systemDevice/postAddDevice',
        payload: {
          roleDeviceIdList: this.state.roleDevicePowerList,
          sreRoleId: this.state.curRoleId,
        },
      }).then(() => {
        message.success('操作成功');
        this.setState({ isShowModel: false, checkedKeys: [] });
      });
    } else {
      message.warning('请选择设备');
      return;
    }
  }
  render() {
    return (
      <div className={styles.container}>
        <div style={{ clear: 'both' }}>
          <div className={styles['dev-search']}>
            <div className={styles['dev-search-select']}>
              <Input
                addonBefore="角色编号"
                type="text"
                onChange={e => {
                  this.setState({ roleId: e.target.value });
                }}
              />
            </div>
            <div className={styles['dev-search-select']}>
              <Input
                addonBefore="角色名称"
                type="text"
                onChange={e => {
                  this.setState({ roleName: e.target.value });
                }}
              />
            </div>
            <div className={styles['dev-search-select']}>
              <span className={styles['dev-search-select-title']}>角色种类</span>
              <Select defaultValue="" onChange={this.handleChange}>
                <Option value="0">正常</Option>
                <Option value="1">禁用</Option>
              </Select>
            </div>
            <Button
              type="link"
              className={styles['search']}
              onClick={() => {
                this.searchHandle();
              }}
            >
              搜索
            </Button>
          </div>
        </div>
        <div className={styles.tableArea}>
          <Table dataSource={this.state.tableData} pagination={false} rowKey="roleId">
            <Column title="角色编号" align="center" dataIndex="roleId" key="roleId" />
            <Column title="角色名称" align="center" dataIndex="roleName" key="roleName" />
            <Column
              title="角色状态"
              align="center"
              dataIndex="status"
              key="status"
              render={(_text: number, _record: any) => (
                <span>{_record.status === 0 ? '正常' : '禁用'}</span>
              )}
            />
            <Column title="创建时间" align="center" dataIndex="createTime" key="createTime" />
            <Column
              title="操作"
              align="center"
              key="action"
              render={(_text: number, _record: any) => (
                <span>
                  <a
                    onClick={() => {
                      this.getTreeData(_record);
                    }}
                  >
                    分配设备数据权限
                  </a>
                </span>
              )}
            />
          </Table>
        </div>
        <div className={styles.pageArea}>
          <Pagination
            className={styles.pageHandle}
            showQuickJumper={true}
            defaultCurrent={1}
            pageSize={10}
            total={+this.state.pageTotal}
            onChange={this.onPageChange}
          />
        </div>
        <Spin
          indicator={<Icon type="loading" style={{ fontSize: 24 }} spin={true} />}
          spinning={this.state.isPatching}
        />
        <Modal
          visible={this.state.isShowModel}
          title="分配设备数据权限"
          centered={true}
          // onOk={this.handleOk}
          className="device_box"
          onCancel={() => {
            this.setState({ isShowModel: false });
          }}
          footer={null}
        >
          <div>
            <span className={styles.mr50}>角色编号：{this.state.curRoleId}</span>
            <span>角色名称：{this.state.curRoleName}</span>
          </div>
          <div>
            <p>设备数据权限：</p>
            <Tree
              checkable={true}
              // checkStrictly
              onExpand={this.onExpand}
              expandedKeys={this.state.expandedKeys}
              autoExpandParent={this.state.autoExpandParent}
              onCheck={this.onCheck}
              checkedKeys={this.state.checkedKeys}
              // onSelect={this.onSelect}
              // selectedKeys={this.state.selectedKeys}
            >
              {this.renderTreeNodes(this.state.selcTree)}
            </Tree>
            <div className={styles.btnArea}>
              <Button
                style={{ width: 180, height: 40, float: 'none' }}
                onClick={() => {
                  this.addDevicePower();
                }}
                type="primary"
              >
                确定
              </Button>
            </div>
          </div>
        </Modal>
      </div>
    );
  }
}

export default connect(({ loading, systemDevice }: any) => ({
  loading: loading.effects['systemDevice/applyDeviceTreeData'],
  systemDevice: systemDevice.applyDeviceLists,
  treeData: systemDevice.applyDeviceTreeData,
}))(DevicePermissionManage);
